package controller

import (
	"errors"
	"gin-learn-notes/core/response"
	"gin-learn-notes/logger"
	"gin-learn-notes/request"
	"gin-learn-notes/service"
	"gin-learn-notes/utils"
	"github.com/go-playground/validator/v10"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	var req request.RegisterRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		//判断是否为validator错误
		var ve validator.ValidationErrors
		if errors.As(err, &ve) {
			filedMap := map[string]string{
				"Name": "用户名",
				"Age":  "年龄",
			}
			msg := utils.TranslateValidationError(ve, filedMap)
			c.JSON(http.StatusBadRequest, gin.H{"error": msg})
		} else {
			// 其他绑定错误，如 JSON 格式错误
			c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式不正确"})
		}
		return
	}

	user, err := service.RegisterUser(req)
	if err != nil {
		utils.Fail(c, "保存用户失败:"+err.Error())
	}

	c.JSON(http.StatusOK, gin.H{
		"user_id": user.ID,
	})
}

func GetUserInfo(c *gin.Context) {
	var req request.GetUserInfoRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Fail(c, "参数错误")
		return
	}

	user, err := service.GetUserByID(req.ID)
	if err != nil {
		utils.Fail(c, "用户不存在")
		return
	}
	utils.Success(c, user)
}

func UpdateUser(c *gin.Context) {
	var req request.UpdateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		var ve validator.ValidationErrors
		if errors.As(err, &ve) {
			filedMap := map[string]string{
				"Name": "用户名",
				"Age":  "年龄",
			}
			utils.Fail(c, utils.TranslateValidationError(ve, filedMap))
		} else {
			utils.Fail(c, "参数格式不正确")
		}
		return
	}
	if err := service.UpdateUser(req); err != nil {
		utils.Fail(c, "用户信息更新失败："+err.Error())
		return
	}
	utils.Success(c, nil)
}

func DeleteUser(c *gin.Context) {
	var req request.DeleteUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Fail(c, "参数错误")
		return
	}
	err := service.DeleteUser(req.ID)
	if err != nil {
		utils.Fail(c, "用户删除失败："+err.Error())
		return
	}
	utils.Success(c, nil)
}

func UserList(c *gin.Context) {
	var req request.UserListRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Fail(c, "参数错误")
		response.Fail(c, response.ParamError, "获取用户列表失败："+err.Error())
		return
	}

	users, total, err := service.GetUserList(req)
	if err != nil {
		response.Fail(c, response.ServerError, "获取用户列表失败："+err.Error())
		return
	}
	logger.Log.Info("用户列表：", users)
	response.Success(c, response.PageData{
		List:     users,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
}

// 获取用户个人信息（优先缓存）
func GetUserProfile(c *gin.Context) {
	//var req request.GetUserInfoRequest
	//if err := c.ShouldBindJSON(&req); err != nil {
	//	response.Fail(c, response.ParamError, "参数错误")
	//	return
	//}

	userID := utils.GetUserID(c)
	logger.Log.Info("UserID:", userID)
	if userID == 0 {
		response.Fail(c, response.Unauthorized, "未登录或 token 无效")
		return
	}
	//调用服务层的redis缓存方法
	user, err := service.GetUserProfileWithCache(userID)
	if err != nil {
		response.Fail(c, response.NotFound, "用户不存在")
		return
	}
	// 返回成功响应，返回用户信息
	response.Success(c, user)
}

func Login(c *gin.Context) {
	var req request.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Fail(c, response.ParamError, "参数错误")
	}

	res, err := service.DoLogin(req.Username, req.Password)
	if err != nil {
		response.Fail(c, response.Unauthorized, "用户名或密码错误")
		return
	}

	response.Success(c, gin.H{
		"token":    res.Token,
		"user_id":  res.UserID,
		"username": res.Username,
	})
}
